﻿using UnityEditor;
using UnityEngine;

public enum WidgetType : int
{
    Sprite,
    Label,
}

public class FindWidget : EditorWindow
{
    private static UIPanel panel;
    private MonoBehaviour behaviour;
    private WidgetType widgetType;
    private string resContent;
   
    public static void CreateWindow(UIPanel control)
    {
        var window = GetWindow<FindWidget>("FindWidget");
        window.minSize = new Vector2(280, 80);
        panel = control; window.Show();
    }

    void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        widgetType = (WidgetType)EditorGUILayout.EnumPopup("WidgetType *", widgetType);

        GUI.SetNextControlName("Browse");
        if (GUILayout.Button("Browse", GUILayout.Width(60f)))
        {
            FindWidgetByName();
            GUI.FocusControl("Browse");
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        resContent = EditorGUILayout.TextField("ResContent *", resContent);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        behaviour = EditorGUILayout.ObjectField("Behaviour *", behaviour, typeof(MonoBehaviour), false) as MonoBehaviour;
        EditorGUILayout.EndHorizontal();
        
        EditorGUILayout.BeginHorizontal();
        panel = EditorGUILayout.ObjectField("UIPanel *", panel, typeof(UIPanel), true) as UIPanel;
        EditorGUILayout.EndHorizontal();
    }

    void FindWidgetByName()
    {
        if (panel == null || behaviour == null)
        {
            Debug.LogError("参数错误，请先设置UIPanel, MonoBehaviour");
            return;
        }

        UIWidget[] widgets = panel.GetComponentsInChildren<UIWidget>(true);
        for (int i = 0; i < widgets.Length; i++)
        {
            UISprite sprite = widgets[i] as UISprite;
            UILabel label = widgets[i] as UILabel;

            if (widgetType == WidgetType.Label && label != null)
            {
                if (label.bitmapFont == behaviour && label.text == resContent)
                {
                    Debug.Log("Widget Path == " + NGUITools.GetHierarchy(label.gameObject));
                }
            }
            else if (widgetType == WidgetType.Sprite && sprite != null)
            {
                if (sprite.atlas == behaviour && sprite.spriteName == resContent)
                {
                    Debug.Log("Widget Path == " + NGUITools.GetHierarchy(sprite.gameObject));
                }
            }
        }
    }
}